<script setup lang="ts">
import { onMounted, ref, nextTick } from 'vue'
import type { TCommonProblem } from '../../../../Types/system'
import { QuillEditor } from '@vueup/vue-quill' // 需要安装 @vueup/vue-quill
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {
	addCommonProblem,
	deleteCommonProblem,
	getCommonProblem
} from '../../../../api/system/problem'
import { ElMessage, ElMessageBox } from 'element-plus'
import { standardDateTime } from '../../../../Tools/Time/date'

// 初始化
const loading = ref(true)
const problemList = ref<TCommonProblem[]>([])
const problemDialogVisible = ref(false)
const problemDialogTitle = ref('')
const previewDialogVisible = ref(false) // 预览对话框
const defaultForm: TCommonProblem = {
	title: '',
	content: ''
}
const currentProblem = ref<TCommonProblem>({ ...defaultForm })

// 配置 Quill 编辑器选项
const editorOptions = {
	placeholder: '请输入内容...',
	formats: [
		'bold',
		'italic',
		'underline',
		'strike',
		'blockquote',
		'code-block',
		'header',
		'list',
		'indent'
	],
	clipboard: {
		matchVisual: false
	},
	// 禁用 DOM 突变观察器
	mutationObserver: {
		enabled: false
	}
}
// 工具栏配置
const toolbarOptions = [
	['bold', 'italic', 'underline', 'strike'],
	['blockquote', 'code-block'],
	[{ header: 1 }, { header: 2 }],
	[{ list: 'ordered' }, { list: 'bullet' }],
	[{ indent: '-1' }, { indent: '+1' }],
	['clean']
]

// 添加对编辑器的引用
const quillEditor = ref()

// 获取问题列表
const getProblemList = async () => {
	try {
		const res = await getCommonProblem()
		problemList.value = res.data.data
	} catch (error) {
		ElMessage.error('获取问题列表失败')
	} finally {
		loading.value = false
	}
}

// 添加问题
const openProblemDialog = () => {
	problemDialogTitle.value = '添加常见问题'
	currentProblem.value = { ...defaultForm }

	// 等待 DOM 更新后重置编辑器
	nextTick(() => {
		// 重新创建编辑器实例（由于组件的更新机制，置空需要重新创建实例）
		if (quillEditor.value) {
			quillEditor.value.setHTML('')
		}
	})

	problemDialogVisible.value = true
}

// 编辑问题
const editProblem = (row: TCommonProblem) => {
	problemDialogTitle.value = '编辑常见问题'
	problemDialogVisible.value = true
	currentProblem.value = {
		id: row.id,
		title: row.title,
		content: row.content
	}
}

// 预览问题
const previewProblem = () => {
	if (!currentProblem.value) {
		ElMessage.warning('标题和内容不能为空')
		return
	}
	previewDialogVisible.value = true
}

// 提交问题
const submitProblem = async () => {
	if (!currentProblem.value.title || !currentProblem.value.content) {
		ElMessage.warning('标题和内容不能为空')
		return
	}

	try {
		await addCommonProblem({
			...currentProblem.value
		})
		ElMessage.success('添加成功')
		problemDialogVisible.value = false
		getProblemList() // 刷新列表
	} catch (error) {
		ElMessage.error('添加失败')
	}
}

// 删除问题
const deleteProblem = async (id: number) => {
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			const res = await deleteCommonProblem(id)
			if (res.data.code === 1) {
				ElMessage.success('删除成功')
				getProblemList()
			} else {
				ElMessage.error(`删除失败(${res.data.msg})`)
			}
		})
		.catch(() => {
			ElMessage.info('已取消删除')
		})
}

onMounted(() => {
	getProblemList()
})
</script>

<template>
	<el-card class="problem-card">
		<template #header>
			<div class="card-header">
				<h2>常见问题管理</h2>
				<el-button type="primary" @click="openProblemDialog">
					<el-icon><Plus /></el-icon>添加问题
				</el-button>
			</div>
		</template>

		<!-- 问题列表 -->
		<el-table :data="problemList" max-height="250" style="width: 100%">
			<el-table-column prop="createTime" label="创建时间" width="180">
				<template #default="{ row }">
					{{ standardDateTime(row.createTime) }}
				</template>
			</el-table-column>
			<el-table-column prop="title" label="标题" width="180" />
			<el-table-column prop="content" label="内容" show-overflow-tooltip width="260" />
			<el-table-column label="操作" width="120" fixed="right">
				<template #default="{ row }">
					<el-button-group>
						<el-button type="primary" link @click="editProblem(row)">编辑</el-button>
						<el-button type="danger" link @click="deleteProblem(row.id)">删除</el-button>
					</el-button-group>
				</template>
			</el-table-column>
		</el-table>

		<!-- 添加/编辑问题对话框 -->
		<el-dialog v-model="problemDialogVisible" :title="problemDialogTitle" width="70%">
			<el-form :model="currentProblem" label-position="top">
				<el-form-item label="标题">
					<el-input v-model="currentProblem.title" placeholder="请输入问题标题" />
				</el-form-item>
				<el-form-item label="内容" class="quill-editor-container">
					<div class="editor-wrapper">
						<QuillEditor
							ref="quillEditor"
							v-model:content="currentProblem.content"
							contentType="html"
							theme="snow"
							:options="editorOptions"
							:toolbar="toolbarOptions"
						/>
					</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="problemDialogVisible = false">取消</el-button>
				<el-button type="info" @click="previewProblem">预览</el-button>
				<el-button type="primary" @click="submitProblem">确定</el-button>
			</template>
		</el-dialog>

		<!-- 预览对话框 -->
		<el-dialog v-model="previewDialogVisible" title="预览" center width="40%">
			<h3>{{ currentProblem.title }}</h3>
			<div v-html="currentProblem.content"></div>
		</el-dialog>
	</el-card>
</template>

<style scoped lang="scss">
.problem-card {
	min-width: 100vh;
	margin-top: 20px;

	:deep(.ql-container) {
		height: 300px;
	}
}

.editor-wrapper {
	width: 100%;

	:deep(.ql-editor) {
		min-height: 200px;
	}

	:deep(.ql-toolbar),
	:deep(.ql-container) {
		width: 100% !important;
	}
}

:deep(.el-dialog) {
	.el-dialog__body {
		padding: 20px 30px;
	}

	.el-form {
		.el-form-item {
			margin-bottom: 20px;
			width: 100%;

			&.quill-editor-container {
				.quill-editor {
					display: block !important;
					width: 100% !important;
				}
			}
		}
	}
}

// 标题输入框样式
:deep(.el-input) {
	.el-input__wrapper {
		padding: 8px 12px;
	}
}

// 对话框footer样式
:deep(.el-dialog__footer) {
	padding: 15px 30px 20px;
	border-top: 1px solid #dcdfe6;
}
</style>
